<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 用户列表区域 -->
      <el-table :data="userList" style="width: 100%" border stripe fit>
        <el-table-column type="index" label="ID"></el-table-column>
        <el-table-column prop="avatar" label="头像" width="120">
					<template slot-scope="scope">
					  <img :src="scope.row.avatar_wechat ? scope.row.avatar_wechat : (api_url + scope.row.avatar) " width="80px" height="80px" />
					</template>
				</el-table-column>
        <el-table-column prop="username" label="用户名"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role" label="角色"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.state" @change="userStateChanged(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <el-tooltip effect="dark" content="修改" placement="top" :enterable="false">
              <!-- 修改按钮 -->
              <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row._id)"></el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="删除" placement="top" :enterable="false">
              <!-- 删除按钮 -->
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserById(scope.row._id)"></el-button>
            </el-tooltip>
            <!-- <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false"> -->
              <!-- 分配角色按钮 -->
              <!-- <el-button type="warning" icon="el-icon-setting" size="mini" @click="setRole(scope.row)"></el-button> -->
            <!-- </el-tooltip> -->
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]" :page-size="queryInfo.pagesize" layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>

    </el-card>

    <!-- 添加用户的对话框 -->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="addDialogClose">
      <!-- 内容主体区域 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="80px">
        <!-- 用户头像 -->
        <el-form-item label="头像" prop="avatar">
          <el-upload
            class="avatar-uploader"
            :action="api_upload"
						:multiple="true"
            :show-file-list="false"
            :on-success="handleAvatarSuccess">
            <img v-if="addForm.avatar" :src=" api_url + addForm.avatar" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
				<!-- 用户名 -->
				<el-form-item label="用户名" prop="username">
				  <el-input v-model="addForm.username"></el-input>
				</el-form-item>
        <!-- 密码 -->
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" type="password"></el-input>
        </el-form-item>
        <!-- 手机 -->
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
				<!-- 角色 -->
				<el-form-item label="角色" prop="role">
				  <el-select v-model="addForm.role" placeholder="请选择角色">
				    <el-option label="管理员" value="admin"></el-option>
				    <el-option label="商家" value="business"></el-option>
				    <el-option label="用户" value="normal"></el-option>
				  </el-select>
				</el-form-item>
				<!-- 用户身份 收货地址 -->
				<el-form-item label="收货地址" prop="receiving_address" v-if="addForm.role == 'normal'">
				  <el-col :span="15">
				    <!-- <el-form-item> -->
				      <el-input v-model="addForm.receiving_address" style="margin-right: 5px;"></el-input>
				    <!-- </el-form-item> -->
				  </el-col>
				  <el-col class="line" :span="7"> 请填写完整地址</el-col>
				</el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改对话框 -->
    <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%" @close="editDialogClose">
      <!-- 内容主体区域 -->
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="80px">
        <!-- 用户名 -->
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <!-- 手机 -->
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
				<!-- 收货地址 -->
				<el-form-item label="收货地址" prop="receiving_address">
				  <el-input v-model="editForm.receiving_address"></el-input>
				</el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色的对话框 -->
    <el-dialog title="分配角色" :visible.sync="setRoleDialogVisible" width="50%" @close="setRoleDialogClosed">
      <div>
        <p>当前的用户：{{ userInfo.username }}</p>
        <p>当前的角色：{{ userInfo.role_name }}</p>
        <p>分配新角色：
          <el-select v-model="selectedRoleId" placeholder="请选择角色">
            <el-option v-for="item in rolesList" :key="item.id" :label="item.roleName" :value="item.id">
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
export default {
  data () {
    // 验证手机号码的规则
    var checkMobile = (rule, value, callback) => {
      // 验证手机号的正则表达式
      const regMobile = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) {
        // 合法的邮箱
        return callback()
      }
      callback(new Error('请输入合法的手机号'))
    }

    return {
			api_url: this.$api_url,
			api_upload: this.$api_upload,
      // 获取用户列表的参数对象
      queryInfo: {
        query: '',
        // 当前的页数
        pagenum: 1,
        // 当前每页显示多少条数据
        pagesize: 2
      },
      userList: [],
      total: 0,
      // 控制添加用户对话框的显示和隐藏
      addDialogVisible: false,
      // 添加用户的表单数据
      addForm: {
				avatar: '',
        username: '',
        password: '',
        role: '',
        mobile: '',
				receiving_address: ''
      },
      // 添加表单的验证规则对象
      addFormRules: {
				avatar: [{
				  required: true,
				  message: '请选择用户头像',
				  trigger: 'blur'
				}],
        username: [{
          required: true,
          message: '请输入用户名',
          trigger: 'blur'
        },
        {
          min: 3,
          max: 10,
          message: '用户名的长度在 3 到 10 个字符',
          trigger: 'blur'
        }
        ],
        password: [{
          required: true,
          message: '请输入密码',
          trigger: 'blur'
        },
        {
          min: 6,
          max: 15,
          message: '密码的长度在 5 到 15 个字符',
          trigger: 'blur'
        }
        ],
        mobile: [{
          required: true,
          message: '请输入手机号码',
          trigger: 'blur'
        },
        {
          validator: checkMobile,
          trigger: 'blur'
        }
        ],
				role: [{
				  required: true,
				  message: '请输入身份',
				  trigger: 'blur'
				}
				],
				receiving_address: [{
				  required: true,
				  message: '请输入收货地址',
				  trigger: 'blur'
				}]
      },
      // 控制修改用户对话框的显示和隐藏
      editDialogVisible: false,
      // 查询到的用户信息对象
      editForm: {},
      // 修改表单的验证对象
      editFormRules: {
        mobile: [{
          required: true,
          message: '请输入用户手机',
          trigger: 'blur'
        },
        {
          validator: checkMobile,
          trigger: 'blur'
        }
        ],
				receiving_address: [{
				  required: true,
				  message: '请输入收货地址',
				  trigger: 'blur'
				}]
      },
      // 控制分配角色对话框的显示与隐藏
      setRoleDialogVisible: false,
      // 需要被分配角色的用户信息
      userInfo: {},
      // 所有角色列表数据
      rolesList: [],
      // 已选中的角色Id值
      selectedRoleId: '',
			
    }
  },
  created () {
    this.getUserList()
  },
  methods: {
		handleAvatarSuccess(res, file) {
		  this.addForm.avatar = res[0].file;
			console.log(this.addForm.avatar);
		},
    async getUserList () {
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo
      })
			// console.log(res)
      if (res.code !== 200) return this.$message.error(res.msg)
      this.userList = res.data.data;
			this.userList.forEach(item=>{
				if (item.avatar&&item.avatar.indexOf('thirdwx.qlogo.cn') != -1) {
					item.avatar_wechat = item.avatar;
				}
			})
      this.total = res.data.total
      console.log(this.userList);
    },
    // 监听pagesize改变的事件
    handleSizeChange (newSize) {
      // console.log('pagesize:' + newSize)
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    // 监听页码值改变的事件
    handleCurrentChange (newPage) {
      // console.log('pagenum:' + newPage)
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    // 监听switch开关状态的改变
    async userStateChanged (userinfo) {
      console.log(userinfo)
      const {
        data: res
      } = await this.$http.put(`users/${userinfo._id}/state/${userinfo.state}`)
			console.log('sate',res);
			// return;
      if (res.code !== 200) {
        userinfo.state = !userinfo.state;
        return this.$message.error(res.msg)
      }
      this.$message.success(res.msg)
    },
    // 监听添加用户对话框的关闭事件
    addDialogClose () {
      // this.addForm = ''
      this.$refs.addFormRef.resetFields()
    },
    // 点击按钮添加新用户
    addUser () {
      this.$refs.addFormRef.validate(async valid => {
        // console.log(vaild)
        if (!valid) return
        // 可以发送添加用户的网络请求
        const {
          data: res
        } = await this.$http.post('users', this.addForm)
				
        if (res.code !== 200) {
          this.$message.error(res.msg)
        }
        this.$message.success(res.msg)
        // 隐藏添加用户的对话框
        this.addDialogVisible = false
        this.getUserList()
      })
    },
    // 展示编辑用户的对话框
    async showEditDialog (id) {
      const { data: res } = await this.$http.get('users/' + id)
			console.log(res);
      if (res.code !== 200) return this.$message.error(res.msg)
      this.editForm = res.data;
      this.editDialogVisible = true
    },
    // 监听修改用户对话框的关闭事件
    editDialogClose () {
      this.$refs.editFormRef.resetFields()
    },
    // 修改用户信息并提交
    editUserInfo () {
      this.$refs.editFormRef.validate(async valid => {
        // console.log(valid)
        if (!valid) return
        // 发起修改用户信息的数据请求
				console.log('editForm',this.editForm);
        const {
          data: res
        } = await this.$http.put('users/' + this.editForm._id, {
          receiving_address: this.editForm.receiving_address,
          mobile: this.editForm.mobile
        })
				console.log(res);
        if (res.code !== 200) {
          return this.$message.error(res.msg)
        }
        // 关闭对话框
        this.editDialogVisible = false
        // 刷新数据列表
        this.getUserList()
        // 提示修改成功
        this.$message.success(res.msg)
      })
    },
    async removeUserById (id) {
      // 弹框询问用户是否删除数据
      const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 如果用户确认删除,则返回值为字符串 confirm
      // 如果用户取消了删除,则返回值为字符串 cancel
      // console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除！')
      }
      const { data: res } = await this.$http.delete('users/' + id)
      if (res.code !== 200) {
        return this.$message.error(res.msg)
      }
      this.$message.success(res.msg)
      this.getUserList()
    },
    // 展示分配角色的对话框
    async setRole (userInfo) {
      this.userInfo = userInfo
      // 在展示对话框之前,所有的角色列表
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败！')
      }
      this.rolesList = res.data
      console.log(this.rolesList)
      this.setRoleDialogVisible = true
    },
    // 点击按钮,分配角色
    async saveRoleInfo () {
      if (!this.selectedRoleId) {
        return this.$message.error('请选择要分配的角色！')
      }
      const { data: res } = await this.$http.put(`users/${this.userInfo.id}/role`, { rid: this.selectedRoleId })
      if (res.meta.status !== 200) {
        return this.$message.error('更新角色失败！')
      }
      this.$message.success('更新角色成功！')
      this.getUserList()
      this.setRoleDialogVisible = false
    },
    // 监听分配角色对话框的关闭事件
    setRoleDialogClosed () {
      this.selectedRoleId = ''
      this.userInfo = {}
    }
  }
}
</script>

<style lang="less" scoped>
	[class*=el-col-] {
		margin-right: 5px;
	}
	/deep/ .avatar-uploader .el-upload {
	    border: 1px dashed #d9d9d9;
	    border-radius: 6px;
	    cursor: pointer;
	    position: relative;
	    overflow: hidden;
	  }
	  .avatar-uploader .el-upload:hover {
	    border-color: #409EFF;
	  }
	  .avatar-uploader-icon {
	    font-size: 28px;
	    color: #8c939d;
	    width: 90px;
	    height: 90px;
	    line-height: 90px;
	    text-align: center;
	  }
	  .avatar {
	    width: 90px;
	    height: 90px;
	    display: block;
	  }
</style>
